package m

import (
	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"

	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"
)

type Static struct {
	Typ int64 `bson:"typ" json:"typ"`
	Num int64 `bson:"num" json:"num"`
}

type UserStatic struct {
	BaseM
	Uid     bson.ObjectId     `bson:"_id" json:"uid"`
	Statics map[int64]*Static `bson:"statics" json:"statics"`
}

func NewUserStatic() cache.EntryI {
	return &UserStatic{Statics: make(map[int64]*Static, 0)}
}

// 保存信息
func (uStatic *UserStatic) Save() (err error) {
	if uStatic.Statics == nil || len(uStatic.Statics) == 0 {
		return
	}

	err = dbmodule.MgoDB.GameDB.Upsert("userStatic", bson.M{"_id": uStatic.Uid}, uStatic)
	if err != nil {
		return
	}
	return
}

func (uStatic *UserStatic) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		uStatic.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		uStatic.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "UserSet_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return uStatic.LoadData()
}

// 加载数据
func (uStatic *UserStatic) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("userStatic", bson.M{"_id": uStatic.Uid}, nil, &uStatic)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	if uStatic.Statics == nil {
		uStatic.Statics = make(map[int64]*Static, 0)
	}
	return
}

// 更新数据
func (uStatic *UserStatic) Update(val *UserStatic) {
	Cache.Put("userStatic", uStatic.Uid.Hex(), val)
	val.UpdateData()
}

func (uStatic *UserStatic) AddTypNum(typ, num int64) {
	defer uStatic.Update(uStatic)
	if v, ok := uStatic.Statics[typ]; ok {
		v.Num += num
		return
	}

	uStatic.Statics[typ] = &Static{Typ: typ, Num: num}
}

func (u *User) GetUserStatic() *UserStatic {
	v, _ := Cache.Get("userStatic", u.Uid.Hex())
	return v.(*UserStatic)
}
